//
//  UPWebViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/24.
//

#import "UPWebViewController.h"
#import <Masonry/Masonry.h>
#import <StoreKit/StoreKit.h>
#import "UPNetworkManager.h"
//#import "UPTrackingManager.h"
#import "UPSchemeManager.h"
#import "UPUserDefaults.h"

@interface UPWebViewController ()

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) double startTime;

@end

@implementation UPWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupWebView];
    [self loadWebContent];
    [self setupCustomBackButton];
    self.startTime = [[NSDate date] timeIntervalSince1970];
}

- (void)setupCustomBackButton {
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_back"]
                                                                   style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector(backButtonTapped)];
    self.navigationItem.leftBarButtonItem = backButton;
    self.navigationItem.hidesBackButton = YES;
}

- (void)backButtonTapped {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    } else {
        if (self.isFollowOrder) {
            if (self.isPresent) {
                [self dismissViewControllerAnimated:YES completion:nil];
            } else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        } else {
            if (self.isPresent) {
                [self dismissViewControllerAnimated:YES completion:nil];
            } else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)dealloc {
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"aviarium"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"existacle"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"year"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"cardischoolality"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"dynaette"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"brevimemoryty"];
}

#pragma mark - UI Setup

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupProgressView];
}

- (void)setupProgressView {
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    self.progressView.tintColor = [UIColor colorWithHexString:@"#1E4FF3"];
    self.progressView.trackTintColor = [UIColor clearColor];
    
    [self.view addSubview:self.progressView];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.leading.trailing.equalTo(self.view);
        make.height.equalTo(@2);
    }];
}

#pragma mark - WebView Setup

- (void)setupWebView {
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    
    // 添加消息处理器
    [userContentController addScriptMessageHandler:self name:@"campaignery"];
    [userContentController addScriptMessageHandler:self name:@"reveal"];
    [userContentController addScriptMessageHandler:self name:@"himself"];
    [userContentController addScriptMessageHandler:self name:@"experienceite"];
    [userContentController addScriptMessageHandler:self name:@"sculpt"];
    [userContentController addScriptMessageHandler:self name:@"anguite"];
    
    config.userContentController = userContentController;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view insertSubview:self.webView belowSubview:self.progressView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.progressView.mas_bottom);
        make.leading.trailing.bottom.equalTo(self.view);
    }];
}

#pragma mark - Load Content

- (void)loadWebContent {
    NSString *queryString = [[[UPNetworkManager sharedManager] commonParameters] dicToURLQueryStr];
    NSString *urlString = self.urlString;
    
    if (urlString && [urlString containsString:@"?"]) {
        urlString = [[NSString stringWithFormat:@"%@&%@", urlString, queryString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    } else {
        urlString = [[NSString stringWithFormat:@"%@?%@", urlString ?: @"", queryString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    if (urlString) {
        NSURL *url = [NSURL URLWithString:urlString];
        if (url) {
            [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
        }
    }
}

#pragma mark - Progress Observer

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {
        self.progressView.progress = self.webView.estimatedProgress;
        self.progressView.hidden = self.webView.estimatedProgress >= 1.0;
    }
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"campaignery"]) {
        [self handleMaiDianWithMessage:message];
    } else if ([message.name isEqualToString:@"reveal"]) {
        [self handleJumpAppOrH5WithMessage:message];
    } else if ([message.name isEqualToString:@"himself"]) {
        [self closeCurrentH5WithMessage:message];
    } else if ([message.name isEqualToString:@"experienceite"]) {
        [self jumpToHomeVcWithMessage:message];
    } else if ([message.name isEqualToString:@"sculpt"]) {
        [self callPhoneWithMessage:message];
    } else if ([message.name isEqualToString:@"anguite"]) {
        [self appMarkWithMessage:message];
    }
}

- (void)handleMaiDianWithMessage:(WKScriptMessage *)message {
    if (![message.body isKindOfClass:[NSArray class]]) {
        NSLog(@"无效的消息格式");
        return;
    }
    
    NSArray *body = (NSArray *)message.body;
    if (body.count < 2) {
        NSLog(@"消息体长度不足");
        return;
    }
    
    NSInteger productId = 0;
    id firstObject = body[0];
    if ([firstObject isKindOfClass:[NSNumber class]]) {
        productId = [firstObject integerValue];
    } else if ([firstObject isKindOfClass:[NSString class]]) {
        productId = [firstObject integerValue];
    } else {
        NSLog(@"无法解析 productId");
        return;
    }
    
    NSString *productNum = body[1];
    if (![productNum isKindOfClass:[NSString class]]) {
        NSLog(@"无法解析 productNum");
        return;
    }
    
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    [UPReportDataManager reportToMaiDian:UPSceneTypeEndLoan
                               productId:[NSString stringWithFormat:@"%ld", (long)productId]
                              productNum:productNum
                          startTimeStamp:self.startTime
                            endTimeStamp:currentTime];
}

- (void)handleJumpAppOrH5WithMessage:(WKScriptMessage *)message {
    if ([message.body isKindOfClass:[NSString class]]) {
        NSString *url = (NSString *)message.body;
        if ([url hasPrefix:@"http"] || [url hasPrefix:@"https"]) {
            UPWebViewController *webviewVC = [[UPWebViewController alloc] init];
            webviewVC.urlString = url;
            [self.navigationController pushViewController:webviewVC animated:YES];
        } else {
            [[UPSchemeManager shared] parser:url];
        }
    }
}

- (void)closeCurrentH5WithMessage:(WKScriptMessage *)message {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)jumpToHomeVcWithMessage:(WKScriptMessage *)message {
    [self.navigationController popToRootViewControllerAnimated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIViewController *rootVC = [UIApplication up_currentKeyWindow].rootViewController;
        if ([rootVC isKindOfClass:[UPTabBarViewController class]]) {
            UPTabBarViewController *mainVC = (UPTabBarViewController *)rootVC;
            [mainVC changeViewControllerToIndex:0];
        }
    });
}

- (void)callPhoneWithMessage:(WKScriptMessage *)message {
    if ([message.body isKindOfClass:[NSString class]]) {
        NSString *email = (NSString *)message.body;
        [self openEmailComposer:email];
    }
}

- (void)openEmailComposer:(NSString *)email {
    NSString *phone = [UPUserDefaults stringForKey:loginPhoneNumberKey] ?: @"";
    NSString *urlstr = [NSString stringWithFormat:@"mailto:%@?body=Upang Pasti,%@:", email, phone];
    NSString *mailtoUrlString = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:mailtoUrlString];
    if (url && [[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
}

- (void)appMarkWithMessage:(WKScriptMessage *)message {
    if (@available(iOS 10.3, *)) {
        [SKStoreReviewController requestReview];
    }
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    self.title = webView.title;
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
    
    NSURL *url = navigationAction.request.URL;
    NSLog(@"用户点击了链接: %@", url.absoluteString);
    
    if ([url.absoluteString containsString:@"special-link"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
}

@end
